package com.summer.dingding.controller;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiUserListbypageRequest;
import com.dingtalk.api.response.OapiUserListbypageResponse;
import com.summer.core.annotations.ScopeType;
import com.summer.core.service.BaseService;
import com.summer.dingding.model.DingDingUser;
import com.summer.dingding.service.DingDingMessageService;
import com.summer.dingding.service.DingDingService;
import com.summer.dingding.util.DingDingUtil;
import com.summer.user.model.User;
import com.taobao.api.ApiException;

@Component
@Scope(ScopeType.VIEW)
public class DingDingHome {

	@Resource
	HibernateTemplate ht;
	
	@Resource
	BaseService<Object> baseService;
	
	@Resource
	DingDingService dingDingService;
	
	@Resource
	DingDingMessageService dingDingMessageService;
	
	private String hasImage;
	
	private String imageUrl;
	
	private String form;
	
	private String userId;
	
	public String sendOAMessage() {
		
//		dingDingMessageService.buildSendMessage("http://mia.summor.cn", title, content, "老夏", image, form)
		return null;
	}
	
	
	
	public void batchSyncUser() throws ApiException {
		DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/listbypage");
		OapiUserListbypageRequest request = new OapiUserListbypageRequest();
		request.setDepartmentId(90875944l);
		request.setOffset(0L);
		request.setSize(100L);
		request.setOrder("entry_desc");
		request.setHttpMethod("GET");
		OapiUserListbypageResponse response = client.execute(request,DingDingUtil.getAppAccesstoken());
		System.out.println(response.getBody());
		JSONArray array = JSONArray.parseArray(JSONObject.parseObject(response.getBody()).getString("userlist"));
		List<DingDingUser> duserList = JSONObject.parseArray(array.toJSONString(), DingDingUser.class);
		for (DingDingUser duser : duserList) {
			System.out.println(duser.getUserid() + " " + duser.getName() + " " + duser.getJobnumber());
			List<DingDingUser> dUserList = ht.find("from DingDingUser duser where duser.userid = ? and duser.unionid = ?", duser.getUserid(), duser.getUnionid());
			if(dUserList == null || dUserList.size() == 0) {
				List<User> userList = ht.find("from User user where user.realname=?", duser.getName());
				User user = userList.get(0);
				duser.setId(duser.getUserid());
				duser.setUser(user);
				duser.setBindStatus("1");
				baseService.save(duser);
			} else {
				DingDingUser duser1 = dUserList.get(0);
				if(duser1.getBindStatus() == null || !duser1.getBindStatus().equals("1")) {
					duser1.setBindStatus("1");
					baseService.merge(duser1);
				}
			}
		}
	}
}
